const express = require("express");
const app = express();

const server = require("http").createServer(app)
const io = require("socket.io")(server)

// 托管静态资源
app.use(express.static("public"));

let count = 0;
io.on("connection", (socket) => {
    count++;
    io.emit("count", count); // 当前人数
    // 用户进入房间
    socket.on("username", (data) => {
        socket.username = data;
        io.emit("enterRoom", {
            username: socket.username,
            state: 1 // 自定义状态
        });
    });
    // 用户头像
    socket.on("userAvatar", (data) => {
        socket.avatar = data;
    })
    // 监听用户发言
    socket.on("speak", (data) => {
        io.emit("userSpeak", {
            username: socket.username,
            speak: data,
            avatar: socket.avatar,
            state: 2,
        });
    });
    // 断开连接/离开房间
    socket.on('disconnect', function () {
        io.emit("leaveRoom", {
            username: socket.username,
            state: 0
        });
        count--;
        io.emit("count", count);
    });
});

// 启动服务，端口号默认 80
server.listen(80, () => {
    console.log("server running at http://localhost");
})